package com.lnlyj.media;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import com.lnlyj.media.data.load.LoadManager;
import com.lnlyj.media.data.load.QueryFactory;
import com.lnlyj.media.ui.MediaActivity;

import androidx.fragment.app.Fragment;

/**
 * wanglei 2020-04-18
 */
public final class LnlyjSelector {

    public static final String TAG = "LnlyjSelector";

    private static volatile LnlyjSelector instance;
    private Config globalConfig = new Config();

    private final Application application;

    private LnlyjSelector(Application app, Config config) {
        this.application = app;
        if (config != null) {
            this.globalConfig = config;
        }
    }

    public static LnlyjSelector init(LnlyjSelector selector) {
        if (selector == null) {
            throw new RuntimeException("LnlyjSelector init, selector not be null");
        }
        synchronized (LnlyjSelector.class) {
            if (instance == null) {
                instance = selector;
            } else {
                Log.e(TAG, "LnlyjSelector is already init");
            }
        }
        LoadManager.getInstance().loadAlbumData(null);
        LoadManager.getInstance().loadMediaData(QueryFactory.getMediaConfig(-1), null);
        return instance;
    }

    public static LnlyjSelector getInstance() {
        if (instance == null) {
            throw new RuntimeException("must init LnlyjSelector once");
        }
        return instance;
    }

    public Application getApplication() {
        return application;
    }

    public void clearCache() {
        LoadManager.getInstance().clearCache();
    }

    public void setGlobalConfig(Config globalConfig) {
        this.globalConfig = globalConfig;
    }

    public Config getGlobalConfig() {
        return globalConfig;
    }

    public void selector(Activity activity) {
        selector(activity, globalConfig);
    }

    public void selector(Activity activity, Config config) {
        MediaActivity.call(activity, config);
    }

    public void selector(Fragment fragment) {
        selector(fragment, globalConfig);
    }

    public void selector(Fragment fragment, Config config) {
        MediaActivity.call(fragment, config);
    }

    public static class Builder {
        private final Application application;
        private Config config;

        public Builder(Application app) {
            this.application = app;
        }

        public Builder globalConfig(Config config) {
            this.config = config;
            return this;
        }


        public LnlyjSelector build() {
            return new LnlyjSelector(application, config);
        }
    }

}
